/** @jsx React.createElement */
/** @jsxRuntime classic */
/** @jsxFrag React.Fragment */
import React, { useState, useRef, useEffect } from "react";
import styles from './CustomerService.module.css';
import ParticleBackground from './ParticleBackground';

type MessageType = 'user' | 'agent' | 'system';

interface Message {
    type: MessageType;
    content: string;
    complete?: boolean;
    messageId?: string;
    timestamp?: number;
}

// 本地存储键名
const CHAT_HISTORY_KEY = 'customer_service_chat_history';
const CHAT_MODE_KEY = 'customer_service_mode';

export default function CustomerService() {
    // 从本地存储加载历史聊天记录和模式
    const loadChatHistory = (): Message[] => {
        try {
            const savedHistory = localStorage.getItem(CHAT_HISTORY_KEY);
            return savedHistory ? JSON.parse(savedHistory) : [{ 
                type: 'agent', 
                content: '您好！我是您的智能客服小艺，请问有什么可以帮您？',
                timestamp: Date.now()
            }];
        } catch (error) {
            console.error('加载聊天历史失败:', error);
            return [{ 
                type: 'agent', 
                content: '您好！我是您的智能客服小艺，请问有什么可以帮您？',
                timestamp: Date.now()
            }];
        }
    };

    const loadChatMode = (): 'ai' | 'human' => {
        try {
            return (localStorage.getItem(CHAT_MODE_KEY) as 'ai' | 'human') || 'ai';
        } catch {
            return 'ai';
        }
    };

    const [currentMode, setCurrentMode] = useState<'ai' | 'human'>(loadChatMode());
    const [messages, setMessages] = useState<Message[]>(loadChatHistory());
    const [isVisible, setIsVisible] = useState(true);
    const [status, setStatus] = useState(`当前模式：${loadChatMode() === 'ai' ? '智能助手' : '人工客服'}`);
    const [inputValue, setInputValue] = useState('');
    const wsRef = useRef<WebSocket | null>(null);
    const messagesEndRef = useRef<HTMLDivElement>(null);
    const processedMessageIds = useRef<Set<string>>(new Set());
    const chatBodyRef = useRef<HTMLDivElement>(null);

    // 保存聊天历史到本地存储
    useEffect(() => {
        localStorage.setItem(CHAT_HISTORY_KEY, JSON.stringify(messages));
    }, [messages]);

    // 保存聊天模式到本地存储
    useEffect(() => {
        localStorage.setItem(CHAT_MODE_KEY, currentMode);
    }, [currentMode]);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const connect = () => {
        if (wsRef.current) {
            wsRef.current.close();
        }
        
        const ws = new WebSocket(`ws://localhost:3000/ws`);
        wsRef.current = ws;
        
        ws.onopen = () => {
            updateStatus('已连接到人工客服系统');
            ws.send(JSON.stringify({
                type: 'register',
                role: 'customer'
            }));
        };

        ws.onclose = () => {
            updateStatus('与人工客服断开连接，正在重连...');
            setTimeout(connect, 3000);
        };

        ws.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'message') {
                    // 检查消息是否已处理
                    if (data.messageId && processedMessageIds.current.has(data.messageId)) {
                        console.log('已忽略重复消息:', data.messageId);
                        return;
                    }
                    
                    // 记录消息ID
                    if (data.messageId) {
                        processedMessageIds.current.add(data.messageId);
                        
                        // 限制缓存大小
                        if (processedMessageIds.current.size > 100) {
                            const firstValue = processedMessageIds.current.values().next().value;
                            if (firstValue) {
                                processedMessageIds.current.delete(firstValue);
                            }
                        }
                    }
                    
                    // 显示消息
                    if (typeof data.content === 'string') {
                        addMessage(data.content, 'agent');
                    }
                }
            } catch (error) {
                console.error('解析消息错误:', error);
            }
        };
    };

    const exec = (prompt: string) => {
        const serverUrl = 'http://localhost:3000'; // 修改为你的服务器地址和端口
        const url = new URL(`${serverUrl}/users/chat`, window.location.href);
        url.searchParams.set('prompt', prompt);

        const es = new EventSource(url);
        let accumulatedContent = '';

        es.onmessage = (event) => {
            const data = event.data || '';
            if (data === '[DONE]') {
                console.log('done...');
                es.close();
                return;
            }

            try {
                const obj = JSON.parse(data);
                let content = '';
                
                if (obj.choices && obj.choices[0]) {
                    if (obj.choices[0].delta && obj.choices[0].delta.content) {
                        content = obj.choices[0].delta.content;
                    } else if (obj.choices[0].message && obj.choices[0].message.content) {
                        content = obj.choices[0].message.content;
                    } else {
                        console.log('Unexpected response format:', obj);
                        return;
                    }
                }

                if (content === null || content === undefined) {
                    console.log('stop...');
                    es.close();
                    return;
                }

                accumulatedContent += content;
                setMessages(prev => {
                    const newMessages = [...prev];
                    const lastMessage = newMessages[newMessages.length - 1];
                    if (lastMessage && lastMessage.type === 'agent' && !lastMessage.complete) {
                        lastMessage.content = accumulatedContent;
                    } else {
                        newMessages.push({ 
                            type: 'agent', 
                            content: accumulatedContent, 
                            complete: false,
                            timestamp: Date.now()
                        });
                    }
                    return newMessages;
                });
            } catch (error) {
                console.error('Error processing message:', error, data);
                addMessage('抱歉，处理响应时出现错误', 'agent');
                es.close();
            }
        };

        es.onerror = (error) => {
            console.error('EventSource error:', error);
            addMessage('抱歉，连接出现错误，请稍后重试', 'agent');
            es.close();
        };
    };

    const addMessage = (content: string, type: MessageType) => {
        setMessages(prev => [...prev, { 
            type, 
            content,
            timestamp: Date.now()
        }]);
    };

    const updateStatus = (status: string) => {
        if (currentMode === 'human') {
            setStatus(`当前模式：人工客服 - ${status}`);
        }
    };

    const toggleChat = () => {
        setIsVisible(prev => !prev);
    };

    const switchMode = (mode: 'ai' | 'human') => {
        // 如果模式没有变化，不做任何操作
        if (mode === currentMode) return;
        
        // 添加系统消息而不是清除历史
        if (mode === 'human') {
            addMessage('为了更好解决您的问题，小艺已切换至人工客服模式', 'agent');
        } else {
            addMessage(`已切换至AI助手模式`, 'system');
        }
        
        // 更新模式和状态
        setCurrentMode(mode);
        setStatus(`当前模式：${mode === 'ai' ? '智能助手' : '人工客服'}`);
        
        // 如果切换到人工客服模式且没有连接，则连接
        if (mode === 'human' && !wsRef.current) {
            connect();
        }
    };

    const handleHotQuestionClick = (question: string) => {
        addMessage(question, 'user');
        exec(question);
    };

    const handleCommonQuestionClick = (question: string) => {
        addMessage(question, 'user');
        exec(question);
    };

    const sendChatMessage = () => {
        if (inputValue.trim() === '') return;

        addMessage(inputValue, 'user');
        
        if (currentMode === 'ai') {
            exec(inputValue);
        } else {
            if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
                wsRef.current.send(JSON.stringify({
                    type: 'message',
                    content: inputValue
                }));
            } else {
                addMessage('抱歉，当前无法连接到人工客服，请稍后再试', 'agent');
            }
        }
        
        setInputValue('');
    };

    const handleChatKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
        if (event.key === 'Enter') {
            sendChatMessage();
        }
    };

    // 添加清除历史功能
    const clearChatHistory = () => {
        setMessages([{ 
            type: 'agent', 
            content: '您好！我是您的智能客服小艺，请问有什么可以帮您？',
            timestamp: Date.now()
        }]);
    };

    // 当模式变化时处理连接
    useEffect(() => {
        if (currentMode === 'human') {
            connect();
        }
        
        // 组件卸载时清理WebSocket
        return () => {
            if (wsRef.current) {
                wsRef.current.close();
            }
        };
    }, [currentMode]);

    // 当前时间
    const currentTime = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    });

    const formatTime = (timestamp: number): string => {
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        });
    };

    // 渲染消息内容，支持链接
    const renderMessageContent = (content: string) => {
        // 简单的链接匹配，可以根据需要扩展
        const urlRegex = /(https?:\/\/[^\s]+)/g;
        const parts = content.split(urlRegex);
        
        return parts.map((part, index) => {
            if (part.match(urlRegex)) {
                return <a key={index} href={part} target="_blank" rel="noopener noreferrer" className={styles.messageLink}>{part}</a>;
            }
            return <span key={index}>{part}</span>;
        });
    };

    return (
        <>
            <div className={styles.particleBackground}>
                <ParticleBackground />
            </div>
            
            <div className={styles.chatWidgetContainer}>
                <div className={styles.chatContainer}>
                    {/* 中间区域 - 聊天窗口 */}
                    <div className={styles.middlePanel}>
                        <div className={styles.chatHeader}>
                            <span>华为智能服务助手</span>
                            <button 
                                onClick={toggleChat} 
                                className={styles.closeButton}
                            >×</button>
                        </div>
                        
                        <div className={styles.chatMessages}>
                            {messages.map((msg, index) => (
                                <div key={index} className={`${styles.message} ${styles[`${msg.type}Message`]}`}>
                                    {msg.type === 'agent' && (
                                        <div className={styles.agentAvatar}>
                                            <img src="/images/agent-avatar.png" alt="智能客服" />
                                        </div>
                                    )}
                                    <div className={styles.messageContent}>
                                        {msg.type === 'agent' && (
                                            <div className={styles.messageHeader}>
                                                <span className={styles.agentName}>小艺</span>
                                                <span className={styles.messageTime}>
                                                    {msg.timestamp ? formatTime(msg.timestamp) : currentTime}
                                                </span>
                                            </div>
                                        )}
                                        <div className={styles.messageText}>
                                            {renderMessageContent(msg.content)}
                                        </div>
                                    </div>
                                </div>
                            ))}
                            <div ref={messagesEndRef} />
                        </div>

                        <div className={styles.chatControls}>
                            <div className={styles.chatModeSwitch}>
                                {currentMode === 'ai' ? (
                                    <button 
                                        className={styles.humanServiceBtn}
                                        onClick={() => switchMode('human')}
                                    >
                                        人工客服
                                    </button>
                                ) : (
                                    <button 
                                        className={styles.aiServiceBtn}
                                        onClick={() => switchMode('ai')}
                                    >
                                        返回智能助手
                                    </button>
                                )}
                                <button 
                                    className={styles.clearHistoryBtn}
                                    onClick={clearChatHistory}
                                >
                                    清空历史
                                </button>
                            </div>

                            <div className={styles.chatInput}>
                                <input 
                                    type="text" 
                                    value={inputValue}
                                    onChange={(e) => setInputValue(e.target.value)}
                                    placeholder="请输入您的问题，小艺将为您解答..." 
                                    onKeyDown={handleChatKeyPress} 
                                />
                                <button 
                                    onClick={sendChatMessage}
                                    className={styles.sendButton}
                                >
                                    发送
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}